<template>
  <view class="container">
    <!-- 搜索栏 -->
    <view class="search-box">
      <u-search
        v-model="keyword"
        placeholder="搜索图书馆"
        :show-action="false"
        @custom="search"
      ></u-search>
    </view>
    
    <!-- 学校选择 -->
    <view class="school-section">
      <u-dropdown ref="schoolDropdown">
        <u-dropdown-item v-model="selectedSchoolId" :title="schoolTitle" :options="schoolOptions"></u-dropdown-item>
      </u-dropdown>
    </view>
    
    <!-- 图书馆列表 -->
    <view class="library-list">
      <view 
        class="library-item" 
        v-for="(item, index) in filteredLibraries" 
        :key="index"
        @click="selectLibrary(item)"
      >
        <image class="library-image" :src="item.image_url || '/static/images/library-default.png'" mode="aspectFill"></image>
        <view class="library-info">
          <view class="library-name">{{ item.name }}</view>
          <view class="library-address">{{ item.address }}</view>
          <view class="library-stats">
            <text class="stat-item">
              <u-icon name="seat" size="24" color="#1A8DFF"></u-icon>
              <text>总座位: {{ item.total_seats }}</text>
            </text>
            <text class="stat-item">
              <u-icon name="clock" size="24" color="#1A8DFF"></u-icon>
              <text>开放时间: {{ item.open_time }}</text>
            </text>
          </view>
        </view>
        <u-icon name="arrow-right" color="#999"></u-icon>
      </view>
    </view>
    
    <!-- 空状态 -->
    <u-empty v-if="filteredLibraries.length === 0" mode="search" text="没有找到相关图书馆"></u-empty>
    
    <!-- 加载更多 -->
    <u-loadmore v-if="filteredLibraries.length > 0" :status="loadStatus" />
  </view>
</template>

<script>
export default {
  data() {
    return {
      keyword: '',
      selectedSchoolId: '',
      schoolOptions: [],
      libraries: [],
      page: 1,
      size: 10,
      total: 0,
      loadStatus: 'loading', // loading, nomore, loadmore
      reserveData: {}
    }
  },
  computed: {
    schoolTitle() {
      if (!this.selectedSchoolId) return '选择学校'
      
      const school = this.schoolOptions.find(item => item.value === this.selectedSchoolId)
      return school ? school.label : '选择学校'
    },
    filteredLibraries() {
      if (!this.libraries.length) return []
      
      let result = this.libraries
      
      // 按学校筛选
      if (this.selectedSchoolId) {
        result = result.filter(item => item.school_id === this.selectedSchoolId)
      }
      
      // 按关键词筛选
      if (this.keyword) {
        const lowerKeyword = this.keyword.toLowerCase()
        result = result.filter(item => 
          item.name.toLowerCase().includes(lowerKeyword) || 
          item.address.toLowerCase().includes(lowerKeyword)
        )
      }
      
      return result
    }
  },
  onLoad() {
    // 获取预约数据
    const reserveData = uni.getStorageSync('reserveData')
    if (reserveData) {
      this.reserveData = JSON.parse(reserveData)
      
      // 如果已有选中的图书馆，设置选中的学校
      if (this.reserveData.libraryId) {
        const library = this.libraries.find(item => item.id === this.reserveData.libraryId)
        if (library) {
          this.selectedSchoolId = library.school_id
        }
      }
    }
    
    this.getSchools()
    this.getLibraries()
  },
  methods: {
    // 获取学校列表
    async getSchools() {
      try {
        const res = await this.$api.getSchools()
        if (res.data && res.data.code === 200) {
          const schools = res.data.data || []
          this.schoolOptions = schools.map(item => ({
            label: item.name,
            value: item.id
          }))
        }
      } catch (error) {
        console.error('获取学校列表失败', error)
        uni.showToast({
          title: '获取学校列表失败',
          icon: 'none'
        })
      }
    },
    
    // 获取图书馆列表
    async getLibraries() {
      try {
        uni.showLoading({
          title: '加载中'
        })
        
        const res = await this.$api.getLibraries({
          page: this.page,
          size: this.size
        })
        
        uni.hideLoading()
        
        if (res.data && res.data.code === 200) {
          const { rows, count } = res.data.data
          
          this.libraries = this.page === 1 ? rows : [...this.libraries, ...rows]
          this.total = count
          
          // 更新加载状态
          if (this.libraries.length >= this.total) {
            this.loadStatus = 'nomore'
          } else {
            this.loadStatus = 'loadmore'
          }
        }
      } catch (error) {
        uni.hideLoading()
        console.error('获取图书馆列表失败', error)
        uni.showToast({
          title: '获取图书馆列表失败',
          icon: 'none'
        })
      }
    },
    
    // 搜索
    search() {
      this.page = 1
      this.libraries = []
      this.getLibraries()
    },
    
    // 选择图书馆
    selectLibrary(library) {
      // 更新预约数据
      this.reserveData.libraryId = library.id
      this.reserveData.libraryName = library.name
      
      // 清除已选择的楼层、区域和座位
      this.reserveData.floorId = ''
      this.reserveData.floorName = ''
      this.reserveData.areaId = ''
      this.reserveData.areaName = ''
      this.reserveData.seatId = ''
      this.reserveData.seatName = ''
      
      // 保存预约数据
      uni.setStorageSync('reserveData', JSON.stringify(this.reserveData))
      
      // 返回上一页
      uni.navigateBack()
    },
    
    // 上拉加载更多
    onReachBottom() {
      if (this.loadStatus === 'nomore') return
      
      this.page++
      this.loadStatus = 'loading'
      this.getLibraries()
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 30rpx;
}

.search-box {
  background-color: #ffffff;
  padding: 20rpx;
}

.school-section {
  margin-bottom: 20rpx;
}

.library-list {
  padding: 0 20rpx;
}

.library-item {
  display: flex;
  align-items: center;
  background-color: #ffffff;
  border-radius: 10rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.library-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
}

.library-info {
  flex: 1;
  margin-right: 20rpx;
}

.library-name {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.library-address {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.library-stats {
  display: flex;
  flex-wrap: wrap;
}

.stat-item {
  display: flex;
  align-items: center;
  font-size: 24rpx;
  color: #999;
  margin-right: 20rpx;
  margin-bottom: 10rpx;
  
  text {
    margin-left: 6rpx;
  }
}
</style>
